import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-03-07
 * Time: 11:32
 */
class Solution24 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(a, b) -> a[0] - b[0]);//升序排序

        List<int[]> lists = new ArrayList<>();
        for(int[] x : intervals){
            int size = lists.size();
            if(size == 0){
                lists.add(x);
            }else{
                int[] lastGroup = lists.get(size-1);
                if(x[0] > lastGroup[1]){
                    lists.add(x);
                }else{
                    lists.remove(size-1);
                    int leftIndex = lastGroup[0];
                    int rightIndex = Math.max(lastGroup[1],x[1]);
                    lists.add(new int[]{leftIndex,rightIndex});
                }
            }
        }
        int size = lists.size();
        int[][] ret = new int[size][];
        for(int i = 0 ; i < ret.length ; i++){
            int[] tmp = lists.get(i);
            ret[i] = tmp;
        }
        return ret;
    }
}
public class Test24 {
}
